package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.iot.IotMsgBody;
import com.zzyl.nursing.vo.iot.IotMsgNotifyData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备数据表Service业务层处理
 * 
 * @author zxy
 * @date 2025-06-02
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询设备数据表
     * 
     * @param id 设备数据表主键
     * @return 设备数据表
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据表列表
     * 
     * @param deviceData 设备数据表
     * @return 设备数据表
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceData)
    {
        Page<DeviceData> page = Page.of(deviceData.getPageNum(), deviceData.getPageSize());
        lambdaQuery().like( DeviceData::getDeviceName, deviceData.getDeviceName())
                .eq(DeviceData::getFunctionId,  deviceData.getFunctionId())
                .gt(DeviceData::getAlarmTime,  deviceData.getStartTime())
                .lt(DeviceData::getAlarmTime, deviceData.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(page);
        return  getTableDataInfo(page);
    }

    /**
     * 封装分页对象
     * @param page
     * @return
     */
    @NotNull
    private static TableDataInfo<DeviceData> getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo<DeviceData> tableData = new TableDataInfo<DeviceData>();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
    /**
     * 新增设备数据表
     * 
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据表
     * 
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据表
     * 
     * @param ids 需要删除的设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据表信息
     * 
     * @param id 设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 保存上传数据
     * @param iotNotifyData
     */
    @Transactional
    @Override
    public void saveBatchInster(IotMsgNotifyData iotNotifyData) {
        //判断设备是否存在
        String iotId = iotNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (device == null){
            log.info("设备不存在");
            return;
        }
        IotMsgBody body = iotNotifyData.getBody();
        body.getServices().forEach(item->{

            //处理时间
            String eventTime = item.getEventTime();
            log.info("开始处理时间");
            //处理上报时间日期
            LocalDateTime activeTime =  LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            log.info("处理时间结束");
            //获取设备属性
            Map<String, Object> properties = item.getProperties();

            List<DeviceData> collect = properties.entrySet().stream()
                    .map(entry -> {
                        DeviceData data = BeanUtil.toBean(device, DeviceData.class);
                        data.setId(null);
                        data.setAlarmTime(alarmTime);
                        data.setFunctionId(entry.getKey());
                        data.setDataValue(entry.getValue().toString());
                        data.setAccessLocation(device.getRemark());
                        data.setCreateTime(null);
                        data.setCreateBy(null);
                        data.setUpdateBy(null);
                        data.setUpdateTime(null);
                        return data;
                    })
                    .collect(Collectors.toList());
            log.info("开始保存数据");
            saveBatch(collect);
            log.info("保存成功");
            stringRedisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(collect));
        });

    }
    }

